<template>
  <div class="map-container">
    <!-- 顶部导航 -->
    <header class="map-header">
      <div class="header-left">
        <i class="el-icon-arrow-left" @click="goBack"></i>
        <span>地图找房</span>
      </div>
      <div class="header-right">
        <i class="el-icon-location-outline" @click="locateCurrentPosition"></i>
      </div>
    </header>

    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入小区名称或地址"
        prefix-icon="el-icon-search"
        @keyup.enter.native="searchLocation"
      ></el-input>
    </div>

    <!-- 地图区域 -->
    <div class="map-content">
      <div class="area-grid">
        <div 
          class="area-item" 
          v-for="(area, index) in filteredAreas" 
          :key="index"
          @click="selectArea(area)"
        >
          <div class="area-info">
            <div class="area-name">{{ area.name }}</div>
            <div class="area-count">{{ area.count }}套房源</div>
            <div class="area-price">{{ area.price }}万/㎡</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 位置详情 -->
    <div class="location-detail" v-if="selectedArea">
      <div class="detail-header">
        <h3>{{ selectedArea.name }}</h3>
        <i class="el-icon-close" @click="closeDetail"></i>
      </div>
      <div class="detail-content">
        <p><strong>地址：</strong>{{ selectedArea.address }}</p>
        <p><strong>房源数量：</strong>{{ selectedArea.count }}套</p>
        <p><strong>均价：</strong>{{ selectedArea.price }}万/㎡</p>
        <p><strong>坐标：</strong>{{ selectedArea.longitude.toFixed(4) }}, {{ selectedArea.latitude.toFixed(4) }}</p>
      </div>
      <div class="detail-actions">
        <el-button type="primary" @click="saveLocation" size="small">保存位置</el-button>
        <el-button @click="viewProperties" size="small">查看房源</el-button>
      </div>
    </div>

    <!-- 保存的位置列表 -->
    <div class="saved-locations" v-if="savedLocations.length > 0">
      <div class="section-title">
        <span>已保存的位置</span>
        <el-button type="text" @click="clearAll">清空</el-button>
      </div>
      <div class="location-list">
        <div 
          class="saved-item" 
          v-for="(location, index) in savedLocations" 
          :key="index"
        >
          <div class="saved-info">
            <div class="saved-name">{{ location.name }}</div>
            <div class="saved-address">{{ location.address }}</div>
            <div class="saved-time">{{ formatTime(location.savedTime) }}</div>
          </div>
          <div class="saved-actions">
            <i class="el-icon-delete" @click="removeLocation(index)"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 定位提示 -->
    <el-dialog
      title="提示"
      :visible.sync="locationDialogVisible"
      width="80%"
    >
      <p>是否允许获取您的位置信息？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="locationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="getLocation">允许</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MapFindHouse',
  data() {
    return {
      searchKeyword: '',
      selectedArea: null,
      savedLocations: [],
      locationDialogVisible: false,
      areas: [
        { name: '浦东新区', count: 1250, price: 6.8, longitude: 121.5447, latitude: 31.2222, address: '上海市浦东新区' },
        { name: '徐汇区', count: 890, price: 7.2, longitude: 121.4368, latitude: 31.1797, address: '上海市徐汇区' },
        { name: '静安区', count: 650, price: 8.5, longitude: 121.4581, latitude: 31.2252, address: '上海市静安区' },
        { name: '黄浦区', count: 420, price: 7.8, longitude: 121.4905, latitude: 31.2317, address: '上海市黄浦区' },
        { name: '长宁区', count: 580, price: 6.8, longitude: 121.4242, latitude: 31.2204, address: '上海市长宁区' },
        { name: '闵行区', count: 980, price: 5.2, longitude: 121.3817, latitude: 31.1125, address: '上海市闵行区' },
        { name: '普陀区', count: 750, price: 5.8, longitude: 121.3958, latitude: 31.2510, address: '上海市普陀区' },
        { name: '虹口区', count: 520, price: 6.2, longitude: 121.5058, latitude: 31.2650, address: '上海市虹口区' }
      ],
      currentLocation: null
    }
  },
  computed: {
    filteredAreas() {
      if (!this.searchKeyword) return this.areas
      return this.areas.filter(area => 
        area.name.includes(this.searchKeyword) || 
        area.address.includes(this.searchKeyword)
      )
    }
  },
  mounted() {
    this.loadSavedLocations()
  },
  methods: {
    selectArea(area) {
      this.selectedArea = area
    },
    
    closeDetail() {
      this.selectedArea = null
    },
    
    locateCurrentPosition() {
      this.locationDialogVisible = true
    },
    
    getLocation() {
      this.locationDialogVisible = false
      
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.currentLocation = {
              longitude: position.coords.longitude,
              latitude: position.coords.latitude
            }
            
            // 找到最近的区域
            const nearestArea = this.findNearestArea(this.currentLocation)
            this.selectedArea = nearestArea
            this.$message.success('定位成功！')
          },
          (error) => {
            console.error('定位失败:', error)
            this.$message.error('定位失败，请检查权限设置')
            // 默认选择浦东新区
            this.selectedArea = this.areas[0]
          }
        )
      } else {
        this.$message.error('浏览器不支持定位功能')
        this.selectedArea = this.areas[0]
      }
    },
    
    findNearestArea(coords) {
      let minDistance = Infinity
      let nearestArea = this.areas[0]
      
      this.areas.forEach(area => {
        const distance = Math.sqrt(
          Math.pow(coords.longitude - area.longitude, 2) + 
          Math.pow(coords.latitude - area.latitude, 2)
        )
        if (distance < minDistance) {
          minDistance = distance
          nearestArea = area
        }
      })
      
      return nearestArea
    },
    
    searchLocation() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键词')
        return
      }
      
      const foundArea = this.areas.find(area => 
        area.name.includes(this.searchKeyword) || 
        area.address.includes(this.searchKeyword)
      )
      
      if (foundArea) {
        this.selectedArea = foundArea
        this.$message.success(`找到位置：${foundArea.name}`)
      } else {
        this.$message.error('未找到相关位置')
      }
    },
    
    saveLocation() {
      if (!this.selectedArea) return
      
      const location = {
        ...this.selectedArea,
        savedTime: new Date().getTime()
      }
      
      this.savedLocations.unshift(location)
      localStorage.setItem('savedLocations', JSON.stringify(this.savedLocations))
      
      this.$message.success('位置保存成功！')
      this.selectedArea = null
    },
    
    viewProperties() {
      if (!this.selectedArea) return
      
      this.$router.push({
        path: '/',
        query: { location: this.selectedArea.name }
      })
    },
    
    removeLocation(index) {
      this.savedLocations.splice(index, 1)
      localStorage.setItem('savedLocations', JSON.stringify(this.savedLocations))
      this.$message.success('位置已删除')
    },
    
    clearAll() {
      this.$confirm('确定要清空所有保存的位置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.savedLocations = []
        localStorage.removeItem('savedLocations')
        this.$message.success('已清空保存的位置')
      }).catch(() => {})
    },
    
    loadSavedLocations() {
      const saved = localStorage.getItem('savedLocations')
      if (saved) {
        this.savedLocations = JSON.parse(saved)
      }
    },
    
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    goBack() {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.map-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 1000;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left i {
  font-size: 20px;
  cursor: pointer;
}

.header-left span {
  font-size: 18px;
  font-weight: 500;
}

.header-right i {
  font-size: 20px;
  cursor: pointer;
  color: #1890ff;
}

.search-section {
  padding: 15px 20px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.map-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.area-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.area-item {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.area-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.area-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.area-count {
  font-size: 14px;
  color: #667eea;
  margin-bottom: 4px;
}

.area-price {
  font-size: 12px;
  color: #999;
}

.location-detail {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20px;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
  z-index: 1000;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-header h3 {
  margin: 0;
  color: #333;
}

.detail-content {
  margin-bottom: 15px;
}

.detail-content p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.saved-locations {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  max-height: 300px;
  overflow-y: auto;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
  z-index: 999;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  font-weight: 500;
}

.location-list {
  padding: 0 20px;
}

.saved-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.saved-item:last-child {
  border-bottom: none;
}

.saved-info {
  flex: 1;
}

.saved-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.saved-address {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.saved-time {
  font-size: 12px;
  color: #999;
}

.saved-actions i {
  font-size: 16px;
  color: #ff4d4f;
  cursor: pointer;
  padding: 5px;
}

@media screen and (max-width: 375px) {
  .area-grid {
    grid-template-columns: 1fr;
  }
  
  .area-item {
    padding: 15px;
  }
}
</style>